package com.adv.controller.base;

import java.util.HashMap;
import java.util.Map;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.adv.util.Constant;

public class BaseController {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@ExceptionHandler
	public ModelAndView exceptionHandler(Exception exception) {
		ModelAndView mv = new ModelAndView("error");
		mv.addObject("exception", exception);
		logger.error(exception.toString());
		if (exception instanceof AuthenticationException) {
			// mv.addObject("msg", "没有认证");
			mv.setViewName("nopermission");
		} else if (exception instanceof AuthorizationException) {
			// mv.addObject("msg", "没有授权");
			mv.setViewName("nopermission");
		}
		return mv;
	}

	// @ResponseBody
	// @RequestMapping("/json")
	// public Object helloxx(String name, Map<String, Object> map) {
	// Map<String, Object> json = new HashMap<String, Object>();
	// json.put("json", "value");
	// return json;
	// }

	protected Map<String, Object> convertField2Map(BindingResult result) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put(Constant.RESULTKEY, Constant.FIELDINVALID);// 字段校验错误
		Map<String, String> fieldErrorMap = new HashMap<String, String>();
		for (FieldError fieldError : result.getFieldErrors()) {
			fieldErrorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
		}
		resultMap.put("msg", fieldErrorMap);
		return resultMap;
	}

	protected String redirect(String url) {
		return "redirect:" + url;
	}

	protected Map<String, Object> failureMsg() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put(Constant.RESULTKEY, Constant.FAILURE);
		return resultMap;
	}
}
